<template>
  <div class="maintenance-plans">
    <div class="header-actions">
      <!-- 修复图标组件使用方式 -->
      <el-button type="primary" @click="dialogVisible = true">
        <el-icon>
          <Plus />
        </el-icon> 新建维护计划
      </el-button>
    </div>

    <!-- 添加搜索卡片 -->
    <el-card class="card-container search-card">
      <div class="search-container">
        <el-input v-model="searchKeyword" placeholder="请输入计划ID搜索" class="search-input">
        </el-input>
        <el-button type="primary" @click="handleSearch" class="search-button">
          搜索
        </el-button>
      </div>
    </el-card>

    <!-- 表格卡片容器 -->
    <el-card class="card-container table-card">
      <!-- 表格部分 -->
      <el-table :data="paginatedData" row-class-name="table-row" class="custom-table rounded-table">
        <el-table-column prop="id" label="计划ID" width="100"></el-table-column>
        <!-- 调整维护任务列宽度 -->
        <el-table-column prop="content" label="维护任务" min-width="150"></el-table-column>
        <!-- 修改维护人员ID列，添加指派按钮 -->
        <el-table-column label="维护人员ID" width="200">
          <template #default="scope">
            <div class="ids-container">
              <span>{{ scope.row.ids ? scope.row.ids.join(', ') : '未指派' }}</span>
              <el-button type="text" size="small" @click="handleAssign(scope.row)">
                指派
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.start) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.end) }}
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="创建用户ID" width="150"></el-table-column>
        <!-- 新增操作列 -->
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新建维护计划弹窗 -->
    <el-dialog v-model="dialogVisible" title="新建维护计划" width="500px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="维护内容" prop="content">
          <el-input v-model="formData.content" type="textarea" rows="4" placeholder="请输入维护计划内容"></el-input>
        </el-form-item>
        <!-- 添加开始时间和结束时间选择器 -->
        <el-form-item label="开始时间" prop="start">
          <el-time-picker v-model="formData.start" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="选择开始时间"
            required></el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end">
          <el-time-picker v-model="formData.end" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="选择结束时间"
            required></el-time-picker>
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="formData.userId" placeholder="请输入用户ID" required></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">返回</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑维护计划弹窗 -->
    <el-dialog v-model="editDialogVisible" title="修改维护计划" width="500px">
      <el-form ref="editFormRef" :model="editFormData" :rules="rules" label-width="80px">
        <el-form-item label="维护内容" prop="content">
          <el-input v-model="editFormData.content" type="textarea" rows="4" placeholder="请输入维护计划内容"></el-input>
        </el-form-item>

        <!-- 修改开始时间为小时、分钟、秒输入框 -->
        <el-form-item label="开始时间" prop="start">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-input v-model.number="editFormData.start.hour" placeholder="小时" type="number" min="0"
                max="23"></el-input>
            </el-col>
            <el-col :span="8">
              <el-input v-model.number="editFormData.start.minute" placeholder="分钟" type="number" min="0"
                max="59"></el-input>
            </el-col>
            <el-col :span="8">
              <el-input v-model.number="editFormData.start.second" placeholder="秒" type="number" min="0"
                max="59"></el-input>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 修改结束时间为小时、分钟、秒输入框 -->
        <el-form-item label="结束时间" prop="end">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-input v-model.number="editFormData.end.hour" placeholder="小时" type="number" min="0"
                max="23"></el-input>
            </el-col>
            <el-col :span="8">
              <el-input v-model.number="editFormData.end.minute" placeholder="分钟" type="number" min="0"
                max="59"></el-input>
            </el-col>
            <el-col :span="8">
              <el-input v-model.number="editFormData.end.second" placeholder="秒" type="number" min="0"
                max="59"></el-input>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="用户ID" prop="userId">
          <el-input type="number" v-model="editFormData.userId" placeholder="请输入用户ID" required>

          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增指派人员对话框 -->
    <el-dialog v-model="assignDialogVisible" title="指派维修人员" width="500px">
      <el-form ref="assignFormRef" :model="assignFormData" label-width="100px">
        <el-form-item label="维护计划ID" prop="maintenanceId">
          <el-input v-model="assignFormData.maintenanceId" readonly></el-input>
        </el-form-item>
        <el-form-item label="选择维修人员" prop="userIds">
          <el-select v-model="assignFormData.userIds" multiple placeholder="请选择维修人员" :loading="isLoadingUsers"
            @change="handleSelectChange">
            <el-option v-for="user in userList" :key="user.id" :label="`${user.name} (ID: ${user.id})`"
              :value="user.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssignSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 在现有导入中添加 watch
import { ref, onMounted, computed, watch } from 'vue';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElIcon, ElSelect, ElOption, ElTimePicker, ElPagination } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

// 响应式数据
const plansData = ref([]);
const allPlansData = ref([]); // 存储完整数据用于搜索
const searchKeyword = ref(''); // 搜索关键词
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 格式化时间 (字符串类型转格式化字符串)
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  // 分割时间字符串为小时、分钟、秒
  const parts = timeStr.split(':');
  if (parts.length !== 3) return ''; // 格式不正确时返回空
  const [hour, minute, second] = parts.map(Number);
  // 确保每个部分都是数字且有效
  if (isNaN(hour) || isNaN(minute) || isNaN(second)) return '';
  return `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
};

// 分页数据计算
const paginatedData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return plansData.value.slice(startIndex, startIndex + pageSize.value);
});

// 获取维护计划数据
const fetchPlansData = async () => {
  try {
    const response = await request.get('/admin/getAllMaintenanceSchedule');
    if (response.code === 200) {
      // 添加调试日志查看原始数据
      console.log('后端返回的维护计划数据:', response.data);
      plansData.value = response.data;
      // 修复：保存完整数据到allPlansData用于搜索
      allPlansData.value = [...response.data];
      total.value = response.data.length;
    } else {
      ElMessage.error('获取维护计划失败: ' + (response.msg || '未知错误'));
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络连接');
    console.error('API请求错误:', error);
  }
};

// 搜索功能实现
const handleSearch = () => {
  currentPage.value = 1; // 搜索后重置到第一页
  if (!searchKeyword.value.trim()) {
    // 搜索框为空，显示所有数据
    plansData.value = [...allPlansData.value];
  } else {
    // 根据计划ID精确搜索
    plansData.value = allPlansData.value.filter(plan => 
      plan.id.toString() === searchKeyword.value.trim()
    );
  }
  total.value = plansData.value.length;
};

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 组件挂载时获取数据
onMounted(() => {
  fetchPlansData();
});

// 添加缺失的新建弹窗控制变量
const dialogVisible = ref(false);
const formRef = ref(null);
const editFormRef = ref(null); // 编辑表单引用
// 修改表单初始值
const formData = ref({
  content: '',
  start: '',
  end: '',
  userId: '' // 确保存在userId字段
})

// 修改编辑表单数据结构，支持LocalTime类型
const editFormData = ref({
  id: 0,
  content: '',
  start: { hour: 0, minute: 0, second: 0 },
  end: { hour: 0, minute: 0, second: 0 },
  userId: null
});

// 修改按钮点击事件 - 解析时间数据
// 添加用户列表相关变量
const userList = ref([]);
const isLoadingUsers = ref(false);

// 获取可选用户列表 - 修复HTTP方法和参数传递
const fetchUsers = async (existingUserIds = []) => {
  isLoadingUsers.value = true;
  try {
    var ids = existingUserIds;
    // 修复：将GET改回POST方法，通过请求体传递参数
    const response = await request.post('/admin/getRepairUsers',
      ids
      , {
        timeout: 10000
      });

    console.log('用户列表接口完整响应:', response);

    if (response && response.code === 200) {
      if (Array.isArray(response.data)) {
        userList.value = response.data;
        console.log('获取到的维修人员列表:', userList.value);
      } else {
        userList.value = [];
        console.error('用户列表数据格式错误，期望数组:', response.data);
        ElMessage.error('用户数据格式错误');
      }
    } else {
      userList.value = [];
      const errorMsg = response?.msg || `请求失败(${response?.code || '未知错误码'})`;
      ElMessage.error(`请求用户列表失败: ${errorMsg}`);
    }
  } catch (error) {
    userList.value = [];
    const errorMsg = error.response?.data?.msg || error.message || '网络请求失败';
    ElMessage.error(`请求用户列表失败: ${errorMsg}`);
    console.error('用户列表请求错误详情:', error);
  } finally {
    isLoadingUsers.value = false;
  }
};

// 编辑按钮点击事件
const handleEdit = (row) => {
  if (!row || !row.id) {
    ElMessage.error('无效的维护计划数据');
    return;
  }

  // 解析开始时间字符串为小时、分钟、秒
  const startParts = row.start?.split(':').map(Number) || [0, 0, 0];
  // 解析结束时间字符串为小时、分钟、秒
  const endParts = row.end?.split(':').map(Number) || [0, 0, 0];

  // 填充编辑表单数据
  editFormData.value = {
    id: row.id,
    content: row.content || '',
    start: {
      hour: startParts[0] || 0,
      minute: startParts[1] || 0,
      second: startParts[2] || 0
    },
    end: {
      hour: endParts[0] || 0,
      minute: endParts[1] || 0,
      second: endParts[2] || 0
    },
    userId: row.userId || null
  };

  editDialogVisible.value = true;
};

// 编辑表单提交处理
const handleEditSubmit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();

    // 构造符合接口要求的提交数据
    const submitData = {
      id: editFormData.value.id,
      content: editFormData.value.content,
      // 将时间对象转换为HH:mm:ss格式字符串
      start: `${editFormData.value.start.hour.toString().padStart(2, '0')}:${editFormData.value.start.minute.toString().padStart(2, '0')}:${editFormData.value.start.second.toString().padStart(2, '0')}`,
      end: `${editFormData.value.end.hour.toString().padStart(2, '0')}:${editFormData.value.end.minute.toString().padStart(2, '0')}:${editFormData.value.end.second.toString().padStart(2, '0')}`,
      userId: Number(editFormData.value.userId) // 确保userId是数字类型
    };

    // 将PUT改回POST方法
    const response = await request.post('/admin/updateMaintenanceSchedule', submitData, {
      headers: {
        'Content-Type': 'application/json'
      },
      timeout: 10000
    });

    // 处理响应（根据接口文档的响应格式）
    if (response && response.code === 200) {
      ElMessage.success('维护计划修改成功');
      editDialogVisible.value = false;
      fetchPlansData(); // 刷新列表
    } else {
      ElMessage.error(`修改失败: ${response?.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('提交编辑表单出错:', error);
    if (error.name !== 'ValidationError') {
      ElMessage.error(`提交失败: ${error.message || '网络异常，请重试'}`);
    }
  }
};

// 新建维护计划提交处理
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();

    // 构造提交数据
    const submitData = {
      content: formData.value.content,
      start: formData.value.start,
      end: formData.value.end,
      userId: Number(formData.value.userId) // 确保userId为数字类型
    };

    // 发送创建请求
    const response = await request.post('/admin/addMaintenanceSchedule', submitData, {
      headers: {
        'Content-Type': 'application/json'
      },
      timeout: 10000
    });

    if (response && response.code === 200) {
      ElMessage.success('维护计划创建成功');
      dialogVisible.value = false;
      fetchPlansData(); // 刷新列表
      // 重置表单
      formRef.value.resetFields();
    } else {
      ElMessage.error(`创建失败: ${response?.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    if (error.name !== 'ValidationError') {
      ElMessage.error(`提交失败: ${error.message || '网络异常，请重试'}`);
    }
  }
};
const editDialogVisible = ref(false); // 添加编辑弹窗控制变量
const assignDialogVisible = ref(false); // 添加指派弹窗控制变量
const assignFormRef = ref(null);
const assignFormData = ref({
  maintenanceId: '',
  userIds: []
});

// 指派按钮点击事件
const handleAssign = async (row) => {
  if (!row || !row.id) {
    ElMessage.error('无效的维护计划数据');
    return;
  }

  // 修复：确保userIds始终是数字数组
  const selectedIds = row.ids ? Array.from(row.ids).map(Number) : [];
  assignFormData.value = {
    maintenanceId: row.id,
    userIds: selectedIds
  };

  // 获取用户列表 - 传递空数组而非null
  await fetchUsers(row.ids && row.ids.length > 0 ? row.ids : []);
  assignDialogVisible.value = true;
};

// 指派提交处理
const handleAssignSubmit = async () => {
  if (!assignFormRef.value) return;

  try {
    await assignFormRef.value.validate();

    const submitData = {
      maintenanceId: assignFormData.value.maintenanceId,
      userIds: assignFormData.value.userIds
    };

    const response = await request.post('/admin/arrangementMaintenanceSchedule', submitData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (response && response.code === 200) {
      ElMessage.success('指派成功');
      assignDialogVisible.value = false;
      // 延迟刷新确保后端数据已更新
      setTimeout(() => {
        fetchPlansData();
      }, 300);
    } else {
      ElMessage.error(`指派失败: ${response?.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('指派提交失败:', error);
    if (error.name !== 'ValidationError') {
      ElMessage.error('网络异常，请重试');
    }
  }
};
const handleSelectChange = () => {
  // 强制刷新响应式数据
  assignFormData.value = {
    ...assignFormData.value,
    userIds: [...assignFormData.value.userIds]
  };
  console.log('选择变更后的用户ID:', assignFormData.value.userIds);
};
</script>

<style scoped>
/* 卡片容器样式 */
.card-container {
  width: 70%;
  margin: 0 auto 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.table-card {
  padding: 20px;
}

/* 搜索卡片样式 */
.search-card {
  padding: 20px;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.search-button {
  white-space: nowrap;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: center;
  position: static;
  bottom: auto;
  left: auto;
  transform: none;
  background-color: transparent;
  padding: 0;
  box-shadow: none;
}

/* 表头样式 */
::v-deep .custom-table .el-table__header-wrapper .el-table__header {
  background-color: #1890ff !important;
}

::v-deep .custom-table .el-table__header th {
  background-color: #1890ff !important;
  color: #fff !important;
  border-bottom: 2px solid white !important;
}

/* 表格行悬浮样式 - 蓝色背景+白色字体+无放大 */
::v-deep .el-table .el-table__row:hover,
::v-deep .custom-table .el-table__body .el-table__row:hover,
::v-deep .el-table__body tr.el-table__row:hover>td {
  background-color: #1890ff !important;
  color: #fff !important;
  /* 恢复白色字体 */
  /* 已删除font-size属性，确保无放大效果 */
}

/* 悬浮行中的文本按钮文字变白 */
::v-deep .el-table__row:hover .el-button--text {
  color: #fff !important;
}

/* 表格圆角样式 */
::v-deep .rounded-table {
  border-radius: 12px !important;
  overflow: hidden !important;
  border: none !important;
}

/* 表头圆角 */
::v-deep .rounded-table .el-table__header-wrapper {
  border-radius: 12px 12px 0 0 !important;
  overflow: hidden !important;
}

/* 修复表格行高度问题 */
::v-deep .el-table__body-wrapper {
  overflow: visible !important;
}

::v-deep .el-table__row {
  height: auto !important;
}

::v-deep .el-table .cell {
  transition: padding 0.3s ease !important;
}

::v-deep .el-table .table-row:hover .cell {
  padding: 12px 15px !important;
}

/* 原有样式保留 */
.maintenance-plans {
  padding: 20px 0;
}

.header-actions {
  margin-bottom: 20px;
  text-align: right;
  padding-right: 15%;
  /* 与70%宽度卡片对齐 */
}

.ids-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 移除重复和冲突样式 */
/* 已删除原有的.el-table相关样式 */
</style>